package v1

import (
	"go-gin-example/pkg/app"
	"go-gin-example/pkg/e"
	"go-gin-example/service/author_service"
	"net/http"

	"github.com/astaxie/beego/validation"
	"github.com/gin-gonic/gin"
	"github.com/unknwon/com"
)

func GetAuthor(c *gin.Context) {
	appG := app.Gin{C: c}
	id := com.StrTo(c.Param("id")).MustInt()
	valid := validation.Validation{}
	valid.Min(id, 1, "id").Message("ID必须大于0")

	if valid.HasErrors() {
		app.MarkErrors(valid.Errors)
		appG.Response(http.StatusOK, e.INVALID_PARAMS, nil)
		return
	}

	authorService := author_service.Author{ID: id}
	exists, err := authorService.ExistByID()
	if err != nil {
		appG.Response(http.StatusOK, e.ERROR_CHECK_EXISTS_AUTHOR_FAIL, nil)
		return
	}

	if !exists {
		appG.Response(http.StatusOK, e.ERROR_NOT_EXIST_AUTHOR_FAIL, nil)
		return
	}

	author, err := authorService.Get()
	if err != nil {
		appG.Response(http.StatusOK, e.ERROR_GET_AUTHOR_FAIL, nil)
		return
	}

	appG.Response(http.StatusOK, e.SUCCESS, author)

}

// 表单校验
type AddAuthorForm struct {
	Name       string `form:"name" valid:"Required;MaxSize(30)"`
	Department string `form:"department" valid:"Required;MaxSize(20)"`
	PhoneNo    string `form:"phone_no" valid:"Required;MaxSize(20)"`
	Age        int    `form:"age" valid:"Required;Min(1)"`
	Gender     int    `form:"gender" valid:"Range(0, 1)"`
}

func AddAuthor(c *gin.Context) {
	var (
		appG = app.Gin{C: c}
		form AddAuthorForm
	)

	httpCode, errCode := app.BindAndValid(c, &form)
	if errCode != e.SUCCESS {
		appG.Response(httpCode, errCode, nil)
		return
	}

	authorService := author_service.Author{
		Name:       form.Name,
		Department: form.Department,
		Age:        form.Age,
		Gender:     form.Gender,
		PhoneNo:    form.PhoneNo,
	}
	if err := authorService.Add(); err != nil {
		appG.Response(http.StatusInternalServerError, e.ERROR_ADD_AUTHOR_FAIL, nil)
		return
	}

	appG.Response(http.StatusOK, e.SUCCESS, nil)

}
